/**
 * 表格状态 缓存页面状态
 * @Author: linzy
 * @Date: 2022-06-23
 * @function useTableState
 * @param {object} props - 页面props
 * @param {object} init - 表格监听初始对象 如 {type: 1}
 * @returns {array} [tableForm, tableFormSet, push];
 * @example
 const [tableForm, tableFormSet, push] = useTableState(props);
*/
import { useLayoutEffect, useState, useMemo } from "react";
const defaultData = { page: 1, limit: 15 };

export default (props, init) => {
  const key = window.location.href;
  const [tableForm, tableFormSet] = useState({});
  useMemo(() => {
    let initData = {};
    if (sessionStorage.hasOwnProperty(key)) {
      initData = JSON.parse(sessionStorage.getItem(key));
      setTimeout(() => {
        sessionStorage.removeItem(key);
      }, 500);
    } else if (init) {
      initData = { ...defaultData, ...init };
    } else {
      initData = { ...defaultData };
    }
    tableFormSet(initData);
    return initData;
  }, [key]);
  // 处理滚动缓存
  useLayoutEffect(() => {
    if (sessionStorage.hasOwnProperty(key + "scrollTop")) {
      let top = +sessionStorage.getItem(key + "scrollTop");
      sessionStorage.removeItem(key + "scrollTop");
      setTimeout(() => {
        window.scrollTo({
          top,
        });
      }, 500);
    }
  }, []);
  function push(url) {
    let scrollTop = document.documentElement.scrollTop;
    sessionStorage.setItem(key, JSON.stringify(tableForm));
    sessionStorage.setItem(key + "scrollTop", scrollTop);
    props.history.push(url);
  }
  return [tableForm, tableFormSet, push];
};
